package org.boot.config;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MemcachedConfig {

    private static final Logger log = LoggerFactory.getLogger(MemcachedConfig.class);

    /*@Bean
    public MemcachedClient memcachedClient() throws Exception {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder("127.0.0.1:11211");
        return builder.build();
    }*/

    @Autowired
    private XMemcachedProperties xMemcachedProperties;

    @Bean(name = "memcachedClientBuilder")
    public MemcachedClientBuilder getBuilder() {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(xMemcachedProperties.getServers());
        // 内部采用一致性哈希算法
        builder.setSessionLocator(new KetamaMemcachedSessionLocator());
        // 操作的超时时间
        builder.setOpTimeout(xMemcachedProperties.getOpTimeout());
        // 采用二进制传输协议（默认为文本协议）
        builder.setCommandFactory(new BinaryCommandFactory());
        // 设置连接池的大小
        builder.setConnectionPoolSize(xMemcachedProperties.getPoolSize());
        // 是否开起失败模式
        builder.setFailureMode(xMemcachedProperties.getFailureMode());
        return builder;
    }

    /**
     * 由Builder创建memcachedClient对象，并注入spring容器中
     *
     * @param memcachedClientBuilder xxx
     * @return MemcachedClient
     */
    @Bean(name = "memcachedClient")
    public MemcachedClient getClient(@Qualifier("memcachedClientBuilder") MemcachedClientBuilder memcachedClientBuilder) {
        MemcachedClient client = null;
        try {
            client = memcachedClientBuilder.build();
        } catch (Exception e) {
            log.info("exception happens when builder memcached client {}", e.toString());
            throw new RuntimeException(e);
        }
        return client;
    }

}
